const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const SQLiteWrapper = require('./sqlite-wrapper');

const app = new Koa();
const router = new Router();
const db = new SQLiteWrapper('./database.db');




app.use(async (ctx, next) => {
    // 设置跨域请求的头信息
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    await next();
});

// 使用 bodyParser 中间件来解析请求体
app.use(bodyParser());

// router.use(async (ctx, next) => {
//     if (!phone) {
//         ctx.body = {}
//         return;
//     }

//     next();
// });

router.get('/user', async (ctx) => {
    // 获取用户列表
    const user = await db.all('SELECT * FROM users');
    ctx.body = user;
});


router.get('/scale', async (ctx) => {
    // 获取显示比例
    const scales = await db.get('SELECT * FROM scales');
    ctx.body = { result: true, data: scales };
});

router.post('/update', async (ctx) => {
    let before_scale = ctx.request.body.before_scale
    let now_scale = ctx.request.body.now_scale
    let phone = ctx.request.body.phone
    let name = ctx.request.body.name
    // 查询符合条件的记录数量
    const countSql = `SELECT COUNT(*) AS count FROM users WHERE phone = '${phone}'`;
    const result = await db.get(countSql);
    const count = result.count;

    if (count !== 1) {
        // 如果记录数量不为 1，则用户不存在
        ctx.body = { result: false, msg: '用户不存在' };
    } else {
        // 如果记录数量为 1，则更新数据
        const updateSql = `UPDATE scales SET scale ='${now_scale}' WHERE 1=1`;
        // 操作记录
        const insertSql = `INSERT INTO logs (phone,name,before_scale,now_scale,create_at) VALUES ('${phone}','${name}','${before_scale}','${now_scale}', '${getFormattedTime()}')`;
        await db.update(updateSql);
        await db.run(insertSql);
        ctx.body = { result: true, data: '' };
    }

});

router.get('/record', async (ctx) => {
    const phone = ctx.query.phone;
    console.log(phone)
    // 查询符合条件的记录数量
    const countSql = `SELECT COUNT(*) AS count FROM users WHERE phone = '${phone}'`;
    const result = await db.get(countSql);
    const count = result.count;

    if (count !== 1) {
        // 如果记录数量不为 1，则用户不存在
        ctx.body = { result: false, msg: '用户不存在' };
    } else {
        // 获取操作记录列表
        const logs = await db.all('SELECT * FROM logs ORDER BY create_at DESC');
        ctx.body = { result: true, data: logs };
    }

});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000, () => {
    console.log('Server started on port 3000');
});


function getFormattedTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    return formattedTime;
}